<?php
/**
 *title
 * @author: lican<364548233@qq.com>
 *Date: 2020/11/26
 *Time: 17:46
 */

namespace App\Http\Services;

use App\Http\Controllers\LoginController;
use App\Http\Helpers\Sign;
use App\Http\Helpers\Sms;
use App\Models\Admin;
use App\Models\LoginRecord;
use App\Models\Role;

class AdminService{

    /**
     *获取管理员详情
     * @author: lican<364548233@qq.com>
     */
    public static function getAdminDeatil($adminId){
        $admin = Admin::select('admins.name', 'admins.head_image', 'admins.role_id', 'roles.name as role_name')
            ->leftJoin('roles', 'roles.id', 'admins.role_id')
            ->where('admins.id', $adminId)
            ->get()
            ->first();
        $loginRecord = LoginRecord::select('ip', 'updated_at')
            ->where('admin_id', $adminId)
            ->orderBy('id', 'desc')
            ->limit(1)
            ->first();
        $loginRecord['address'] = Sign::getCity($loginRecord['ip']) ?? '未知';
        $admin['login_record'] = $loginRecord;
        return MsgService::getMsg(0, ['admin' => $admin]);
    }

    /**
     *管理员删除
     * @author lican<364548233@qq.com>
     */
    public static function delete($admin, $id){
        $admins = Admin::find($id);
        if($admins->status == Admin::STATUS_ON){
            return MsgService::getMsg(100064);
        }
        $admins->delete();
        return MsgService::getMsg(0);
    }

    /**
     *状态切换
     * @author lican<364548233@qq.com>
     */
    public static function changeStatus($admin, $id){
        $admins = Admin::find($id);
        $status = $admins->status > 0 ? Role::STATUSON : Role::STATUSOFF;
        $admins->status = $status;
        $admins->save();
        $adminId = $admins->id;
        $redirectUri = '';

        if($status == Role::STATUSOFF && $admin['id'] == $id){
            $redirectUri = '/login';
            $key = PREFIX . '_auth';
            $key = $key . $adminId;
            app('redis')->del($key);
        }

        return MsgService::getMsg(0, ['redirect_uri' => $redirectUri]);
    }

    /**
     *管理员保存
     * @author lican<364548233@qq.com>
     */
    public static function saveAdmin($admin, $name, $password, $headImage, $roleId, $mobile,$email, $id = 0){
        if(!Sms::check($mobile)){
            return MsgService::getMsg(100050);
        }
        if(!MailService::checkEmail($email)){
            return MsgService::getMsg(100053);
        }
        if(self::checkExist($name, $mobile, $email, $id)){
            return MsgService::getMsg(100057);
        }
        $role = Role::where('status', Role::STATUSON)
            ->find($roleId);
        if(empty($role)){
            return MsgService::getMsg(100070);
        }
        if($id){
            $admin = Admin::find($id);
        }else{
            $admin = new Admin();
        }
        $salt = str_random(8);
        $admin->name = $name;
        $admin->password = md5($password . $salt);
        $admin->head_image = $headImage;
        $admin->salt = $salt;
        $admin->role_id = $roleId;
        $admin->mobile = $mobile;
        $admin->email = $email;
        $admin->status = Admin::STATUS_ON;
        $admin->save();
        return MsgService::getMsg(0);

    }

    /**
     *检验管理员是否存在
     * @author lican<364548233@qq.com>
     */
    public static function checkExist($name, $mobile, $email, $id = 0){
        $admin = Admin::where('name', $name);
        if($mobile){
            $admin->where('mobile', $mobile);
        }
        if($email){
            $admin->where('email', $email);
        }
        if($id){
            $admin->where('id', '!=', $id);
        }
        return $admin->first();

    }

    /**
     *管理员列表
     * @author: lican<364548233@qq.com>
     */
    public static function index($keyword, $page = 1, $pageSize = 10){
        $admin = Admin::select('admins.id', 'admins.name', 'admins.head_image', 'admins.role_id', 'admins.status', 'admins.ip', 'admins.mobile', 'admins.password', 'admins.email', 'roles.name as role_name')
            ->leftJoin('roles', 'roles.id', 'admins.role_id');
        if($keyword){
            $admin->where(function($query) use ($keyword){
                $query->where('admins.name', 'like', "%{$keyword}%")
                    ->orWhere('admins.mobile', 'like', "%{$keyword}%")
                    ->orWhere('admins.email', 'like', "%{$keyword}%")
                    ->orWhere('roles.name', 'like', "%{$keyword}%");
            });
        }
        $total = $admin->count();
        $list = $admin->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->get()
            ->toArray();
        foreach($list as $k => $v){
            $list[$k]['last_login_place'] = self::getLastLoginPlace($v['id']);
        }
        //取出角色brief
        $role = Role::select('id', 'name')
            ->where('status', Role::STATUSON)
            ->get()
            ->toArray();
        return MsgService::getMsg(0, ['total' => $total, 'list' => $list, 'role' => $role]);

    }

    /**
     *获取管理员最后登录地
     * @author lican<364548233@qq.com>
     */
    public static function getLastLoginPlace($adminId){
        $res = LoginRecord::select('ip')
            ->where('admin_id', $adminId)
            ->orderBy('id', 'desc')
            ->first();
        if($res){
            $ip = $res->ip;
            $city = Sign::getCity($ip) ?? '未知';
        }else{
            $city = '未登录';
        }

        return $city;
    }

    /**
     *获取管理员
     * @author: lican<364548233@qq.com>
     */
    public static function getAdmin(){
        $res = Admin::select('id', 'name')
            ->where('status', Admin::STATUS_ON)
            ->get()
            ->toArray();
        return MsgService::getMsg(0, ['list' => $res]);
    }

}
